<!-- 职位管理新增组件 -->
<template>
  <a-drawer
    :width="600"
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> 新增职位 </template>
    <div>
      <a-form :model="formData" ref="refForm" :rules="rules">
        <a-form-item label="公司：" field="companyId">
          <a-select
            :disabled="props.list?.id"
            placeholder="请选择"
            v-model="formData.companyId"
            @change="companySelect"
          >
            <a-option
              v-for="item in companyList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="所属部门：" field="positionDept">
          <a-tree-select
            :fieldNames="{
              key: 'id',
              title: 'name' // 部门的code
            }"
            :disabled="props.list?.id !== formData.companyId"
            :data="deptList"
            v-model="formData.positionDept"
            placeholder="请选择"
          ></a-tree-select>
          <!-- <a-select v-model="formData.positionDept">
            <a-option
              v-for="(item, index) in deptList"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-option>
          </a-select> -->
        </a-form-item>
        <a-form-item label="职位名称：" field="positionName">
          <a-input
            placeholder="请输入"
            v-model="formData.positionName"
            :disabled="!formData.positionDept"
          ></a-input>
        </a-form-item>
        <a-form-item label="职位编码：" field="positionCode">
          <a-input
            placeholder="系统自动生成"
            v-model="formData.positionCode"
            disabled
          ></a-input>
        </a-form-item>
        <a-form-item label="编制人数：" field="headcount">
          <a-input-number
            placeholder="请输入"
            v-model="formData.headcount"
            hide-button
          ></a-input-number>
        </a-form-item>
        <a-form-item label="关联职务：" field="relatedId">
          <a-select v-model="formData.relatedId" placeholder="请选择">
            <a-option v-for="item in jobList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="关联标准职位：" field="">
          <a-select
            v-model="formData.standJobId"
            placeholder="请选择"
            @change="standJobSelect"
          >
            <a-option
              v-for="item in positionStandList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职位类别：" field="positionTypeId">
          <!-- <a-select v-model="formData.positionTypeId" placeholder="请选择">
            <a-option
              v-for="item in positionTypeList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select> -->
          <a-tree-select
            v-model="formData.positionTypeId"
            :fieldNames="{
              key: 'id',
              title: 'name'
            }"
            :data="positionTypeList"
            placeholder="请选择"
            :allow-search="true"
            allow-clear
            :filter-tree-node="filterPositionType"
            @change="positionTypeChange(formData.positionTypeId)"
            ref="positionTypeRef"
          ></a-tree-select>
        </a-form-item>
        <!-- <a-form-item label="职位序列：" field="">
          <a-select v-model="formData.positionSequenceId" placeholder="请选择">
            <a-option></a-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="选择职位说明书模板：" field="templateId">
          <a-select v-model="formData.templateId" placeholder="请选择">
            <a-option
              v-for="item in templateList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职位层级：" field="positionLevelId">
          <a-select v-model="formData.positionLevelId" placeholder="请选择">
            <a-option
              v-for="item in positionLevelList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职级范围：" field="positionRange">
          <!-- <a-select v-model="formData.positionRange" placeholder="请选择">
            <a-option></a-option>
          </a-select> -->
          <a-select
            :disabled="!formData.positionLevelId"
            v-model="formData.positionRange"
            :popup-visible="false"
            @click="openModal"
            placeholder="请选择"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="是否特殊工种：" field="">
          <a-radio-group v-model="formData.isSpecial">
            <a-radio value="是">是</a-radio>
            <a-radio value="否">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否关键职位：" field="">
          <a-radio-group v-model="formData.isKey">
            <a-radio value="是">是</a-radio>
            <a-radio value="否">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="职位使命：" field="">
          <a-textarea
            allowClear
            v-model="formData.remark"
            :maxLength="300"
            :autoSize="{
              minRows: 5
            }"
            placeholder="请输入"
            showWordLimit
          ></a-textarea>
        </a-form-item>
        <a-form-item label="是否设为标准职位：" field="">
          <a-radio-group v-model="formData.isStand">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="2">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否启用该职位：" field="enable">
          <a-radio-group v-model="formData.enable">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="2">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </div>
    <a-modal
      v-model:visible="modalShow"
      @ok="modelOK"
      @cancel="modalShow = false"
    >
      <template #title> 选择职级 </template>
      <div class="radio">
        <a-radio-group v-model="radioShow" style="margin-bottom: 20px">
          <a-radio value="A">单个职级 </a-radio>
          <a-radio value="B">职级范围 </a-radio>
        </a-radio-group>
        <div class="son-radio" v-show="radioShow === 'A'">
          职级：
          <a-input-number
            v-model="positionRangeNum.num"
            :min="positionRangeData[0]?.levelDown"
            :max="positionRangeData[0]?.levelUp"
            style="width: 150px"
          />
        </div>
        <div class="son-radio" v-show="radioShow === 'B'">
          职级范围：
          <a-input-number
            v-model="positionRangeNum.min"
            :min="positionRangeData[0]?.levelDown"
            :max="positionRangeData[0]?.levelUp"
            style="width: 150px"
          />
          <p style="margin: 0 10px">—</p>
          <a-input-number
            v-model="positionRangeNum.max"
            :min="positionRangeNum.min"
            :max="positionRangeData[0]?.levelUp"
            style="width: 150px"
          />
        </div>
      </div>
    </a-modal>
  </a-drawer>
</template>

<script lang="ts" setup>
import { controldataTreeFilter } from '@/utils/utils';
import {
  GetOrganizationList,
  GetOrganizationCompanyId
} from '@/apis/management/organization/organizationManagement';
import {
  GetPositionTypeList,
  GetPositionLevelList
} from '@/apis/management/organization/baseSetting';
import {
  GetPositionTemplate,
  PutPositionTemplateState,
  GetPositionDefaultTemplate
} from '@/apis/management/organization/baseSetting/PositionSystem';
import { validateRules } from '@/utils/common';
import { GetlistData } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  GetJobList,
  CheckPositionList,
  GetPositionStandard,
  GetPositionStandardDetail
} from '@/apis/management/organization/positionManagement';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    list?: any; // 传进来的数据
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'positionAddEmit']);

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emit('update:visible', visible);
  }
});

// 职位名称查重
const validateName = async (val: any, cb: any, type: number) => {
  try {
    if (!val) return;
    let data = {
      name: val,
      id: formData.value.positionDept
    };
    const res = await validateRules(CheckPositionList, data);
    if (res.code) {
      cb(`${res.data}`);
    } else return;
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  positionName: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  positionCode: [],
  companyId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionDept: [
    {
      required: true,
      message: '请选择'
    }
  ],
  headcount: [
    {
      required: true,
      message: '请输入'
    }
  ],
  relatedId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionTypeId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  templateId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionLevelId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionRange: [
    {
      required: true,
      message: '请选择'
    }
  ],
  enable: [
    {
      required: true,
      message: '请选择'
    }
  ]
};

let formData = ref<any>({
  positionName: '', // 职位名称
  positionCode: '', // 职位编码
  companyId: undefined, // 公司id
  positionDept: undefined, // 所属部门
  headcount: undefined, // 编制人数
  relatedId: undefined, // 关联职务
  standJobId: undefined, // 关联标准职位
  positionTypeId: undefined, // 职位类别
  positionType: '', // 职位类别名称
  positionSequenceId: 1, // 职位序列
  templateId: undefined, // 模板id
  positionLevelId: undefined, // 职位层级
  positionRange: undefined, // 职位范围
  isSpecial: '否', // 是否特殊工种
  isKey: '否', // 是否关键职位
  remark: '', // 职位使命
  isStand: 2, // 是否标准职位 1是 2否,
  enable: 1, // 是否启用该职位 1是 2否
  controlItems: []
});

let organizationDeptList = ref<any>([]); // 储存部门类别
let positionTypeList = ref<any>([]); // 储存职位类别
let positionLevelList = ref<any>([]); // 储存职位层级
let companyList = ref<any>([]); // 储存公司类型的数据
let positionStandList = ref<any>([]); // 储存标准职位库数据

let jobList = ref<any>([]); // 储存职务数据

const getData = async () => {
  try {
    const res: any = await Promise.all([
      // 获取组织类型
      GetOrganizationList({}),
      // 获取职位类型
      GetPositionTypeList({}),
      // 获取职位层级
      GetPositionLevelList({
        page: 1,
        size: -1
      }),
      // 获取职务管理数据
      GetJobList({
        page: 1,
        size: -1
      }),
      // 获取公司
      GetlistData({
        type: 1
      }),
      // 获取标准职位列表
      GetPositionStandard({
        page: 1,
        size: -1
      })
    ]);
    organizationDeptList.value = dealTreeData(res[0]);
    positionTypeList.value = res[1];
    positionLevelList.value = res[2].content;
    console.log('====================================');
    console.log(organizationDeptList.value);
    console.log(res);

    console.log('====================================');
    // 处理部门数据
    const ids: number[] = [];
    jobList.value = res[3].content;
    companyList.value = res[4];
    positionStandList.value = res[5].content;
  } catch (error: unknown) {
    console.log(error);
  }
};

// watch(modalVisible, (newVal: boolean, oldVal: boolean) => {
//   if (newVal) getData();
// });

let deptList = ref([]); // 储存当前选择的公司下的部门
const companySelect = async (id: number) => {
  deptList.value = [];
  formData.value.positionDept = undefined;
  deptList.value = await GetlistData({
    type: 2,
    id
  });
};

// 重新组合树数据(根据需要来重组树结构中的属性字段，用来新增判断是否为叶子节点信息)
const dealTreeData = (treeData: any) => {
  const data = treeData.map((item: any) => ({
    ...item,
    ...controldataTreeFilter(item.controlData),
    // 新增叶子节点字段
    isLeaf: item.children ? false : true,
    // 新增是否能被选中字段，默认只能选叶子
    // selectable: item.typeId !== 1 ? true : false,
    // selectable: item.children ? false : true,
    // 如果children为空数组，则置为null
    children:
      item.children && item.children.length ? dealTreeData(item.children) : null
  }));
  return data;
};

// 模糊搜索职位类型
const filterPositionType = (searchValue: string, nodeData: any) => {
  return nodeData.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
};

const templateList = ref([]); // 储存当前模板列表数据

let positionTypeRef = ref();
// 选择职位类型
const positionTypeChange = async (categoryId: number) => {
  try {
    nextTick(async () => {
      formData.value.positionType =
        positionTypeRef.value.selectedValue[0].label;
      formData.value.templateId = undefined;
      templateList.value = [];
      const { content } = await GetPositionTemplate({
        // id: ID,
        page: 1,
        size: -1,
        categoryId
      });
      // templateList.value.push(
      //   content.find((item: any) => item.required === 1 && item.enable === 1)
      // );
      templateList.value = content.filter((item: any) => item.enable === 1);

      console.log(templateList.value);

      formData.value.templateId = templateList.value.find(
        (item: any) => item.required === 1
      )?.id;
      // // templateList.value = content;
      // await GetPositionDefaultTemplate({
      //   defaultId: 1, // 默认传1
      //   categoryId
      // });
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

// 选择标准职位
const standJobSelect = async (id: number) => {
  try {
    const res = await GetPositionStandardDetail({
      id
    });
    formData.value.positionTypeId = res.categoryId;
    formData.value.templateId = res.templateId;

    const { content } = await GetPositionTemplate({
      // id: ID,
      page: 1,
      size: -1,
      categoryId: res.categoryId
    });
    templateList.value.push(
      content.find((item: any) => item.required === 1 && item.enable === 1)
    );

    formData.value.positionType = res.positionType;
    formData.value.positionLevelId = res.positionLevelId;
    formData.value.positionRange = res.positionRange;
    formData.value.isSpecial = res.isSpecial;
    formData.value.isKey = res.isKey;
    formData.value.remark = res.remark;

    console.log(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

let modalShow = ref(false);
const radioShow = ref('A');
const positionRangeData = ref<any>([]); // 储存职位范围数据
// 存储职位范围弹窗数据
const positionRangeNum = reactive({
  num: 0,
  min: 0,
  max: 0
});

// 打开职级范围的弹出框
const openModal = () => {
  if (formData.value.positionLevelId) {
    modalShow.value = true;
    positionRangeNum.min = 0;
    positionRangeNum.max = 0;
    positionRangeNum.num = 0;
  }
};
const modelOK = () => {
  // modalShow.value = false;
  if (positionRangeNum.num) {
    formData.value.positionRange = `${positionRangeNum.num}`;
  } else {
    formData.value.positionRange = `${positionRangeNum.min}~${positionRangeNum.max}`;
  }
};
watch(
  () => formData.value.positionLevelId,
  () => {
    positionRangeData.value = positionLevelList.value.filter(
      (ele: any) => ele.id === formData.value.positionLevelId
    );
    console.log(positionRangeData.value, positionLevelList.value);
  }
);
watch(
  () => radioShow.value,
  () => {
    if (radioShow.value === 'A') {
      positionRangeNum.min = 0;
      positionRangeNum.max = 0;
    } else {
      positionRangeNum.num = 0;
    }
  }
);

watch(
  () => modalVisible.value,
  async (newVal: boolean) => {
    if (newVal) {
      getData();
      if (props.list?.id) {
        formData.value.companyId = await GetOrganizationCompanyId({
          id: props.list?.id
        });
        if (formData.value.companyId !== props.list?.id)
          formData.value.positionDept = props.list.id;
        deptList.value = await GetlistData({
          type: 2,
          id: formData.value.companyId
        });
      }
    }
  }
);

let refForm = ref(); // 储存表单的ref
// 保存
const handleOk = async () => {
  if (await refForm.value.validate()) {
    modalVisible.value = true;
    return;
  }
  emit('positionAddEmit', formData.value);
  formData.value = {
    positionName: '', // 职位名称
    positionCode: '', // 职位编码
    companyId: undefined, // 公司id
    positionDept: undefined, // 所属部门
    headcount: undefined, // 编制人数
    relatedId: undefined, // 关联职务
    standJobId: undefined, // 关联标准职位
    positionTypeId: undefined, // 职位类别
    positionType: '', // 职位类别名称
    positionSequenceId: 1, // 职位序列
    templateId: undefined, // 模板id
    positionLevelId: undefined, // 职位层级
    positionRange: undefined, // 职位范围
    isSpecial: '否', // 是否特殊工种 1是 2否
    isKey: '否', // 是否关键职位 1是 2否
    remark: undefined, // 职位使命
    isStand: 2, // 是否标准职位 1是 2否,
    enable: 1 // 是否启用该职位 1是 2否
  };
  modalVisible.value = false;
};

// 取消
const handleCancel = () => {
  modalVisible.value = false;
  formData.value = {
    positionName: '', // 职位名称
    positionCode: '', // 职位编码
    companyId: undefined, // 公司id
    positionDept: undefined, // 所属部门
    headcount: undefined, // 编制人数
    relatedId: undefined, // 关联职务
    standJobId: undefined, // 关联标准职位
    positionTypeId: undefined, // 职位类别
    positionType: '', // 职位类别名称
    positionSequenceId: 1, // 职位序列
    templateId: undefined, // 模板id
    positionLevelId: undefined, // 职位层级
    positionRange: undefined, // 职位范围
    isSpecial: '否', // 是否特殊工种 1是 2否
    isKey: '否', // 是否关键职位 1是 2否
    remark: undefined, // 职位使命
    isStand: 2, // 是否标准职位 1是 2否,
    enable: 1 // 是否启用该职位 1是 2否
  };
};
</script>

<style scoped lang="less"></style>
